﻿using B.S.Domain.Generateplan;
using B.S.Domain.Process.AssignattributesOneModel;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using Org.BouncyCastle.Asn1.Cmp;
using B.S.Data.MES.API.Applications.CangKu.Command;

namespace B.S.Data.MES.API.Applications.GenerateplanBasicApplication
{
    public class AddGenerateplanBasicCommandHorter:IRequestHandler<AddGenerateplanBasicCommand,APIRequst<int>>
    {
        IBaseRepository<GenerateplanBasic> repository;
        IMediator mediator;

        public AddGenerateplanBasicCommandHorter(IBaseRepository<GenerateplanBasic> repository, IMediator mediator)
        {
            this.repository = repository;
            this.mediator = mediator;
        }

        public async Task<APIRequst<int>> Handle(AddGenerateplanBasicCommand request, CancellationToken cancellationToken)
        {
            var tracebackInfo = new GenerateplanBasic
            {
                GenerateplanBasicTheme = request.GenerateplanBasicTheme,
                GenerateplanBasicOrderNumber = request.GenerateplanBasicOrderNumber,
                SalesOrder = request.SalesOrder,
                DocumentTime = request.DocumentTime,
                Remarks = request.Remarks,
                OrderId = request.OrderId
            };
            // 保存到数据库
            var result = await repository.Add(tracebackInfo);
            
            // 生产计划添加成功后，调用Tel的添加方法
            if (result > 0)
            {
                // 使用生产计划主题作为CanType参数
                await mediator.Send(new AddTelCommand { CanType = request.GenerateplanBasicTheme }, cancellationToken);
            }
            
            return new APIRequst<int>()
            {
                Data = result,
                Msg = "添加成功"
            };
        }
    }
}
